package org.ilc.message;


import org.ilc.push.IDataProvider;
import org.ilc.push.ISendTask;
import org.ilc.push.Message;

public class QueueTimer extends Thread {

	private QueueExecutor executor;
	private IDataProvider dataProvider;
	private boolean running=false;
	private int sleep=3000;
    private ISendTask sendTask;
	public QueueTimer(QueueExecutor executor, IDataProvider dataProvider, ISendTask sendTask, int sleep){
		this.executor=executor;
		this.dataProvider=dataProvider;
		this.sleep=sleep;
        this.sendTask = sendTask;
	}
	
	
	public void startScan(){
		if(this.running){
			return;
		}
		running=true;
		super.start();
	}
	public void stopScan(){
		this.running=false;
	}
	
	@Override
	public void run() {
		Message message = null;
		while (running) {
			try{
				message =dataProvider.next();
				//如果没有消息
				if(null==message){
					sleep(sleep);
				}else{
					//执行发送
					this.executor.execute(message, sendTask);
				}
			}catch(Exception e){
				e.printStackTrace();
				sleep(sleep);
			}finally{
				message=null;
			}
			
		}

	}
	
	private void sleep(int millis){
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e1) {
			
		}
	}


	public boolean isRunning() {
		return running;
	}

}
